package install

import (
	"fmt"
	"io/ioutil"
	"os"
	"path"

	"gitee.com/shaddy/k3sinstall/mylog"
	"gopkg.in/yaml.v2"
)

func UnInstallHookAll(config *K3sConfig) {
	config.runCmdForAllMasters("sh /usr/local/bin/k3s-uninstall.sh")
	config.runCmdForAllNodes("sh /usr/local/bin/k3s-agent-uninstall.sh")
	config.runCmdMasterAndNode(fmt.Sprintf("rm -fr %s", path.Join(config.WorkDir, "k3s")))
	config.runCmdMasterAndNode(fmt.Sprintf("rm -fr %s", path.Join(config.WorkDir, config.PkgFile)))
	config.runCmdMasterAndNode("> /etc/resolv.conf")
	config.runCmdMasterAndNode("rm -fr /usr/share/kuboard")
	configDir, _ := path.Split(config.ConfigFile)
	os.RemoveAll(configDir)
}

func UnInstallHookNodes(config *K3sConfig, node []string) {
	for n := range node {
		for m := range config.Nodes {
			if config.Nodes[m] == node[n] {
				config.runCmdForMaster0(fmt.Sprintf("kubectl drain %s --delete-local-data --force --ignore-daemonsets", config.NHoseName[m]))
				config.runCmdForMaster0(fmt.Sprintf("kubectl delete node  %s", config.NHoseName[m]))
				config.Nodes = append(config.Nodes[:m], config.Nodes[m+1:]...)
				config.NHoseName = append(config.NHoseName[:m], config.NHoseName[m+1:]...)
				break
			}
		}
	}
	config.runCmd(node, "sh /usr/local/bin/k3s-agent-uninstall.sh")
	config.runCmd(node, fmt.Sprintf("rm -fr %s", path.Join(config.WorkDir, "k3s")))
	config.runCmd(node, fmt.Sprintf("rm -fr %s", path.Join(config.WorkDir, config.PkgFile)))
	config.runCmd(node, "> /etc/resolv.conf")
	config.runCmd(node, "rm -fr /usr/share/kuboard")

	context, err := yaml.Marshal(config)
	if err != nil {
		mylog.Error.Fatalf("解析配置文件错误 err: %s", err.Error())
	}
	err = ioutil.WriteFile(config.ConfigFile, context, 0777)
	if err != nil {
		mylog.Warning.Printf("写入配置文件错误 configfile: %s err: %s \n", config.ConfigFile, err.Error())
	}
}
